package com.example.port.service.impl;

import com.example.port.entity.User;
import com.example.port.mapper.UserMapper;
import com.example.port.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    
    @Autowired
    public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }
    
    @Override
    @Transactional
    public User createUser(User user) {
        // 不再加密密码，直接使用明文
        // user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return user;
    }
    
    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }
    
    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
    
    @Override
    @Transactional
    public User updateUser(User user) {
        // 不再加密密码，直接使用明文
        // if (user.getPassword() != null && !user.getPassword().isEmpty()) {
        //     user.setPassword(passwordEncoder.encode(user.getPassword()));
        // }
        userMapper.update(user);
        return user;
    }
    
    @Override
    @Transactional
    public boolean deleteUser(Integer id) {
        return userMapper.delete(id) > 0;
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return userMapper.selectByUsername(username) != null;
    }
}  
